package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"git.oriente.com/devops/ci-docker-gen/service"
	"github.com/sirupsen/logrus"
)

const (
	usage = "usage: ./ci-docker-gen -name appName -tag tag -email email -release"
)

func main() {
	var tag, name, email string
	var release bool
	var waring = true
	flag.StringVar(&tag, "tag", "", "project image tag")
	flag.StringVar(&name, "name", "", "project name")
	flag.StringVar(&email, "email", "", "Author email")
	flag.BoolVar(&release, "release", false, "send release Note")
	flag.Parse()
	logrus.Infof("name: %v, email: %v, tag: %v", name, email, tag)
	if name == "" || tag == "" {
		fmt.Println(usage)
		return
	}
	if !release {
		err := service.GenerateBuildFile(name, tag)
		if err != nil {
			os.Exit(2)
		}
	} else {
		releaseNote := service.NewReleaseNote("./release.yaml")
		releaseNote.Project = name
		releaseNote.Tag = tag
		releaseNote.Author = email
		releaseNote.Branch = service.GetBranchFromCommitId(tag)
		if !service.IsBranchContainsTag(releaseNote.Branch, releaseNote.Tag) {
			releaseNote.Notice = "Notice，tag does not match the branch!"
			waring = false
		}
		if waring {
			if strings.Contains(releaseNote.Tag, "reg") || strings.Contains(releaseNote.Tag, "hot") {
				onlineVersion, err := service.GetOnlineVersion(releaseNote.Project, releaseNote.Tag)
				if err != nil {
					logrus.Errorf("get online version error,%v", err.Error())
					releaseNote.Online.LackCommits = []string{"新应用无法对比,请忽略！"}
				} else {
					releaseNote.Online.Tag = onlineVersion
				}
			}
			if releaseNote.Online.Tag != "" {
				if service.IsNewTagContainsTag(releaseNote.Tag, releaseNote.Online.Tag) {
					releaseNote.Online.Contains = true
				} else {
					releaseNote.Online.LackCommits = service.DiffTag(releaseNote.Tag, releaseNote.Online.Tag)
				}
			}
		}
		_, err := releaseNote.Send()
		if err == nil {
			logrus.Info("send email finish!")
		}
	}

}
